package com.minazuki.signinserver.service;

import com.minazuki.signinserver.pojo.dao.User;
import com.minazuki.signinserver.pojo.dao.UserMapper;
import com.minazuki.signinserver.utils.CodecUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class UserService {
    private static final Logger logger = LoggerFactory.getLogger(SigninService.class);

    @Autowired
    UserMapper mapper;

    public Boolean checkData(String data, int type) {
        User user = new User();
        switch (type) {
            case 1:
                user.setUsername(data);
                break;
        }
        return mapper.selectCount(user) == 0;
    }

    public User queryUser(String username, String password) {
        // 查询
        User record = new User();
        record.setUsername(username);
        User user = mapper.selectOne(record);
        // 校验用户名
        if (user == null) {
            return null;
        }
        // 校验密码
        if (!user.getPassword().equals(CodecUtils.md5Hex(password, user.getSalt()))) {
            return null;
        }
        // 用户名密码都正确
        return user;
    }

    public String authentication(String username, String password) {
        return null;
    }

    public Boolean register(User user) {
        logger.info("用户"+user.getUsername()+"预注册");
        if (mapper.selectCount(new User(user.getUsername())) > 0) return false;
        user.setId(null);
        user.setCreated(new Date());
        String salt = CodecUtils.generateSalt();
        user.setSalt(salt);
        user.setPassword(CodecUtils.md5Hex(user.getPassword(), salt));
        mapper.insertSelective(user);
        return true;
    }
}
